<template>
  <div>
    <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
      <el-descriptions-item>
        <template #label>
          <div style="display: flex">
            <div style="flex: 1;color: #1a1a1a !important;font-weight: bold;text-align-last: center;">
              支付方式
            </div>
          </div>
        </template>
        <div style="display: flex">
          <div
            style="flex: 0.5;color: #1a1a1a !important;font-weight: bold;text-align-last: center;border-right: 1px solid #d5d5d5">
            支付金额
          </div>
          <div style="flex: 0.5;color: #1a1a1a !important;font-weight: bold;text-align-last: center;">
            退款金额
          </div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item
        v-for="(item, index) in payWayDictListAll"
        :key="index"
      >
        <template #label>
          <div style="display: flex">
            <div style="flex: 1">
              <el-select
                v-model="payWayDictListAll[index].moneyType"
                :disabled="item.disable"
                placeholder="请选择"
                style="width: 120px"
                @change="payWayChange($event, index)"
              >
                <el-option
                  v-for="refundDict in payWayDictSelectAll"
                  v-show="refundDict.cssClass != 'disable'"
                  :key="refundDict.dictValue"
                  :disabled="refundDict.disable"
                  :label="refundDict.dictLabel"
                  :value="refundDict.dictValue"
                ></el-option>
              </el-select>
            </div>
            <!--                        <div style="flex: 0.3">-->
            <!--                            <el-tooltip-->
            <!--                                v-if="index === 0"-->
            <!--                                :hide-after="0"-->
            <!--                                class="box-item"-->
            <!--                                content="添加支付方式"-->
            <!--                                effect="dark"-->
            <!--                                placement="left-end"-->
            <!--                            >-->
            <!--                                <el-button class="ml10" type="primary" @click="addPayWay">-->
            <!--                                    <template #icon>-->
            <!--                                        <i-ep-plus/>-->
            <!--                                    </template>-->
            <!--                                </el-button>-->
            <!--                            </el-tooltip>-->
            <!--                            <el-tooltip-->
            <!--                                v-else-if="!item.disable"-->
            <!--                                :hide-after="0"-->
            <!--                                class="box-item"-->
            <!--                                content="删除支付方式"-->
            <!--                                effect="dark"-->
            <!--                                placement="left-end"-->
            <!--                            >-->
            <!--                                <el-button class="ml10" type="danger" @click="removePayWay(index)">-->
            <!--                                    <template #icon>-->
            <!--                                        <i-ep-minus/>-->
            <!--                                    </template>-->
            <!--                                </el-button>-->
            <!--                            </el-tooltip>-->
            <!--                        </div>-->
          </div>
        </template>
        <div style="display: flex">
          <div style="flex: 0.5">
            <el-input
              v-model="payWayDictListAll[index].charges"
              :disabled="true"
              clearable
              placeholder="请输入金额"
              type="number"
            >
              <template #append>元</template>
            </el-input>
          </div>
          <div style="flex: 0.5">
            <el-input
              v-model="payWayDictListAll[index].refundAmountCost"
              :disabled="item.disable"
              clearable
              placeholder="请输入退款金额"
              type="number"
              @blur="payWayRefundAmountBlur()"
            >
              <template #append>元</template>
            </el-input>
          </div>
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script lang="ts">
export default {
  name: "ClinicAllWayList",
}
</script>

<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user.ts";
import {listSysOrgDict} from "@/api/system/sysOrgDict.ts";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 支付类型明细
const payWayDictListAll = ref<any>([]);

// 退费支付方式合计
const refundPayWayDictListTotal = ref<number>(0);

// 支付方式显示list
const payWayDictSelectAll = ref<any>([]);
const firstPayWay = {moneyType: "1", charges: 0.0,} as any;

const emits = defineEmits(["setNetReceipts", "setRefundAmountCost"]);
const props = defineProps({
  amountItem: {
    default: [],
  },
  refundTotalPrice: {
    default: 0,
    type: Number
  },
});

/**
 * 通过orgId key获取对应的机构参
 */
function getDataList() {
  const params = {
    orgId: userInfo.orgId,
    dictType: "pay_way_dict"
  }
  listSysOrgDict(params).then((res) => {
    payWayDictSelectAll.value = res.data 
  })
}

// 初始化支付方式option都为可选状态
function initPayWayDictSelect() {
  payWayDictSelectAll.value.forEach((pay: any) => {
    pay.disable = false;
  });
}

// 支付方式点击事件
function payWayChange(obj: any, index: number) {
  const indexSelect = payWayDictSelectAll.value.findIndex((item: any) => {
    return obj === item.dictValue;
  });
  if (indexSelect > -1) {
    payWayDictListAll.value[index].typeName = payWayDictSelectAll.value[indexSelect].dictLabel;
    // 设置 字典值，用于统一支付操作字段key值统一
    payWayDictListAll.value[index].moneyType = obj
  }
}

// 增加支付方式点击事件
function addPayWay() {
  payWayDictSelectAll.value.forEach((pay: any) => {
    payWayDictListAll.value.forEach((list: any) => {
      if (pay.dictValue === list.moneyType) {
        pay.disable = true;
      }
    });
  });
  // 获取退费支付方式合计金额
  const refundAmountCostThis = refundPayWayDictListTotalFun();
  // if (refundAmountCostThis > props.refundTotalPrice) {
  //     return ElMessage.error("支付方式中【退款金额】合计与申请的退费金额不相符，不能操作，请重新输入")
  // }
  // 剩余未交的金额
  const residue = Number((Number(props.refundTotalPrice) - refundAmountCostThis).toFixed(2));
  const lastObj = payWayDictListAll.value[payWayDictListAll.value.length - 1];
  if (!lastObj.moneyType) {
    return ElMessage.warning("请填写完已经存在支付方式后，再继续增加");
  }
  payWayDictListAll.value.push({refundAmountCost: residue, charges: 0});
  // payWayRefundAmountBlur();
}

// 通过下标删除指定的支付方式点击事件
function removePayWay(index: number) {
  payWayDictSelectAll.value.forEach((pay: any) => {
    if (pay.dictValue === payWayDictListAll.value[index].moneyType) {
      pay.disable = false;
    }
  });
  payWayDictListAll.value.splice(index, 1);
  payWayRefundAmountBlur();
}

/**
 * 退费支付方式
 */
function payWayRefundAmountBlur() {
  // 获取退费支付方式合计金额
  const refundAmountCostThis = refundPayWayDictListTotalFun();
  emits("setRefundAmountCost", refundAmountCostThis.toFixed(2));
  if (refundAmountCostThis != props.refundTotalPrice) {
    return ElMessage.error("支付方式中【退款金额】合计与申请的退费金额不相符，不能操作，请重新输入")
  }
}

// 设置初始化金额
function setFirstCost(charges: number) {
  payWayDictListAll.value[0].charges = Number(charges.toFixed(2));
}

// 获取支付方式list
function getRefundPayWayDictList() {
  return payWayDictListAll.value;
}

// 支付方式合计方法
function refundPayWayDictListTotalFun() {
  let refundAmountCostThis: number = 0.0;
  payWayDictListAll.value.forEach((item: PayWayType) => {
    //@ts-ignore
    refundAmountCostThis += parseFloat(!item.refundAmountCost ? 0.0 : item.refundAmountCost);
  });
  refundPayWayDictListTotal.value = refundAmountCostThis
  return refundAmountCostThis
}

/**
 * 直接传入已经组织好的支付方式
 * @param obj
 */
function settingPayWayAll(obj: any) {
  payWayDictListAll.value = []
  let payWayDictListThis: any = []
  obj.forEach((item: any) => {
    const dictIndex = payWayDictSelectAll.value.findIndex((dict: any) => {
      return item.moneyType === dict.dictValue;
    })
    if (dictIndex > -1) {
      let payWay = payWayDictSelectAll.value[dictIndex]
      payWay.charges = item.charges
      payWay.moneyType = item.moneyType
      payWay.refundAmountCost = item.refundAmountCost
      payWay.cssClass = 'disable'
      payWayDictListThis.push(payWay)
    }
  })
  payWayDictListAll.value = payWayDictListThis
  orderByPayWay()
}

/**
 * 处理排序 将cssClass = 'disable' 的支付方式放到数组最前边
 */
function orderByPayWay() {
  payWayDictListAll.value.sort((a, b) => {
    if ((toRaw(a).cssClass && toRaw(a).cssClass === 'disable') || (toRaw(a).cssClass && toRaw(b).cssClass === 'disable')) {
      return -1;
    } else {
      return 0;
    }
  })
}

function removePayWayAll() {
  payWayDictListAll.value = []
}


/**
 * 根据指定属性对数组元素进行排序的比较函数生成器
 * @param {string} attr - 用于排序的属性名
 * @param {boolean} [rev=true] - 排序方向，true 为升序，false 为降序，默认为升序
 * @returns {function(a: any, b: any): number} - 一个用于数组 sort 方法的比较函数
 */
function sortBy(attr: string, rev: boolean = true): (a: any, b: any) => number {
  // 将布尔值 rev 转换为数字 1 或 -1，用于表示排序方向，若 rev 为 false 则为 -1 表示降序
  const direction = Number(rev) || -1;

  /**
   * 用于数组 sort 方法的比较函数
   * @param {any} a - 数组中的第一个元素
   * @param {any} b - 数组中的第二个元素
   * @returns {number} - 比较结果，小于 0 表示 a 应排在 b 前面，大于 0 表示 a 应排在 b 后面，等于 0 表示两者顺序不变
   */
  return function (a: any, b: any) {
    // 获取元素 a 中指定属性的值
    const valueA = a[attr];
    // 获取元素 b 中指定属性的值
    const valueB = b[attr];
    // 如果 valueA 小于 valueB
    if (valueA < valueB) {
      // 根据排序方向返回相应结果，升序时返回 -1 让 a 排在 b 前
      return direction * -1;
    }
    // 如果 valueA 大于 valueB
    if (valueA > valueB) {
      // 根据排序方向返回相应结果，升序时返回 1 让 a 排在 b 后
      return direction * 1;
    }
    // 如果 valueA 等于 valueB，则返回 0 表示两者顺序不变
    return 0;
  };
}

function tissuePayWayArray(payWayArray: any) {
  payWayDictListAll.value = []
  let payWayDictListThis: any = []
  payWayArray.forEach((item: any) => {
    const payWayDict = {
      moneyType: item.moneyType,
      charges: item.charges,
      refundAmountCost: item.refundAmountCost,
      sort: item.sort,
      disable: item.disable,
      isAutoAdd: item.isAutoAdd,
    }
    payWayDictListThis.push(payWayDict)
  })
  payWayDictListAll.value = payWayDictListThis.sort(sortBy('sort', true))
}

getDataList()

defineExpose({
  initPayWayDictSelect,
  payWayChange,
  setFirstCost,
  getRefundPayWayDictList,
  removePayWay,
  removePayWayAll,
  settingPayWayAll,
  payWayRefundAmountBlur,
  refundPayWayDictListTotalFun,
  tissuePayWayArray
});
</script>

<style lang="scss" scoped></style>
